'use strict';

const { DataTypes } = require('sequelize');
const sequelize = require('../../database/sequelize');
const City = require('./city');

const TravelPlan = sequelize.define(
  'TravelPlan',
  {
    id: {
      type: DataTypes.INTEGER.UNSIGNED,
      primaryKey: true,
      autoIncrement: true,
      comment: '旅行计划ID',
    },
    user_id: {
      type: DataTypes.INTEGER.UNSIGNED,
      allowNull: true,
      comment: '用户ID（可选）',
    },
    city_id: {
      type: DataTypes.INTEGER.UNSIGNED,
      allowNull: true,
      comment: '主要城市ID',
    },
    title: {
      type: DataTypes.STRING(100),
      allowNull: false,
      comment: '计划标题',
    },
    description: {
      type: DataTypes.TEXT,
      allowNull: true,
      comment: '计划描述',
    },
    start_date: {
      type: DataTypes.DATEONLY,
      allowNull: true,
      comment: '出行日期',
    },
    days: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 5,
      comment: '出行天数（用于列表展示）',
    },
    is_public: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false,
      comment: '是否公开',
    },
    status: {
      type: DataTypes.STRING(20),
      allowNull: true,
      defaultValue: 'pending',
      comment: '审核状态: pending/approved/rejected',
    },
    cover_image: {
      type: DataTypes.STRING(255),
      allowNull: true,
      comment: '封面图',
    },
    daily_plans: {
      type: DataTypes.TEXT,
      allowNull: true,
      comment: '每日计划（JSON字符串）',
    },
    is_top: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false,
      comment: '是否置顶',
    },
  },
  {
    tableName: 'travel_plans',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    underscored: true,
  }
);

// 关联：旅行计划 属于 城市
TravelPlan.belongsTo(City, { foreignKey: 'city_id', as: 'city' });

// 初始化表并插入示例数据（仅开发环境）
(async () => {
  try {
    // await TravelPlan.sync({ alter: true });

    const count = await TravelPlan.count();
    if (count === 0) {
      await TravelPlan.bulkCreate([
        {
          title: '东京五日游',
          description: '探索东京的现代与传统文化',
          city_id: null,
          start_date: '2023-10-15',
          is_public: true,
          days: 5,
          cover_image: 'https://picsum.photos/800/400?random=1',
          status: 'approved',
          daily_plans: null,
        },
        {
          title: '巴黎浪漫之旅',
          description: '体验巴黎的艺术与浪漫',
          city_id: null,
          start_date: '2023-11-20',
          is_public: true,
          days: 7,
          cover_image: 'https://picsum.photos/800/400?random=2',
          status: 'pending',
          daily_plans: null,
        }
      ]);
      console.log('✅ 已插入示例旅行计划数据');
    }
  } catch (e) {
    console.error('TravelPlan 模型初始化失败:', e);
  }
})();

module.exports = TravelPlan;